<script setup>
import {ArrowMove20Filled} from "@vicons/fluent"
import {computed, ref, onMounted} from 'vue'
import {Handle, useNode} from '@vue-flow/core'
import CommandList from "@/views/Control/components/CommandList.vue"
import {storeToRefs} from "pinia";
import {useMessage} from 'naive-ui'
import {useUserProfile} from '@/stores/useUserProfile.js'
import {sendToPortByWritable} from "@/utils/toSerial.js";
import {genDateTime} from "@/utils/getDateTime.js";
import {toByteArray} from "@/utils/byteParser.js";

const props = defineProps({
	position: {
		type: Object,
		required: true,
	},
	data: {},
	id: null
})
const message = useMessage()
const {profile, deviceList} = storeToRefs(useUserProfile())
const x = computed(() => `${Math.round(props.position.x)}px`)
const y = computed(() => `${Math.round(props.position.y)}px`)

// 节点中直接存储空指令即可
const cmdList = ref([])
const {node} = useNode()

// 深度监听指令变动,把指令加入到节点的data中(node.data)
watch(cmdList, (newVal, oldVal) => {
	cmdList.value = newVal
	node.data.cmdList = newVal
}, {deep: true})


/**
 * 运行该节点中所有指令
 * @param node 节点对象
 * @param tabList
 * @returns {Promise<void>}
 */
const runAllCmd = async (node, tabList) => {
	// 运行当前Node的所有指令
	const cmdList = node.data.cmdList
	// 逐次发送每条指令
	for (const cmd of cmdList) {
		// 进度条加载
		cmd.loadingBar.start()
		const tab = tabList.find(item => item.label === cmd.deviceName)
		const {params} = cmd
		if (!params) {
			cmd.loadingBar.error()
			message.error("有未提供参数的指令")
			return
		}
		if (!tab.port.writable) {
			message.error("未找到写入流, 请检查串口是否打开!")
			return
		}
		cmd.lastTime = genDateTime()
		//转字节发送到串口
		let buffer = toByteArray(params)
		await sendToPortByWritable(tab.port.writable, buffer)

		//进度条结束
		await new Promise(resolve => setTimeout(resolve, 0)); // 强制刷新UI
		cmd.loadingBar.finish()
	}
}
node.data.callback = runAllCmd
</script>

<template>
	<n-card class="w-180 h-fit hover:bg-sky-900/25" header-class="pt-1 pb-1">
		<template #header>
			<n-text>状态:{{ node.data.execuated ? "已执行" : "未执行" }}</n-text>
		</template>
		<template #default>
			<div class="border border-sky-700 p-1 flex flex-col gap-1 rounded">
				<Handle type="source" :position="data.sourcePosition"/>
				<Handle type="target" :position="data.targetPosition"/>
				<n-space align="center">
					<n-tag class="text-lg" type="info">步骤{{ id }}</n-tag>
					<n-tag class="text-lg" type="warning">类型:{{ data.label }}</n-tag>
					<n-text depth="3" tag="q">建议一个流程中只放置少量指令</n-text>
				</n-space>
				<div class="nodrag nowheel sm:h-52 xl:h-64">
					<!--设置固定高度-->
					<CommandList v-model:command-list="cmdList" :device-list="deviceList"></CommandList>
				</div>
			</div>
		</template>
	</n-card>
</template>
